from sqlalchemy.orm import Session
from typing import List, Optional
from models import Furniture
from schemas import FurnitureCreate, FurnitureUpdate

# 创建家具
def create_furniture(db: Session, furniture: FurnitureCreate) -> Furniture:
    db_furniture = Furniture(**furniture.dict())
    db.add(db_furniture)
    db.commit()
    db.refresh(db_furniture)
    return db_furniture

# 获取所有家具
def get_furniture_list(db: Session, skip: int = 0, limit: int = 100) -> List[Furniture]:
    return db.query(Furniture).offset(skip).limit(limit).all()

# 根据ID获取家具
def get_furniture(db: Session, furniture_id: int) -> Optional[Furniture]:
    return db.query(Furniture).filter(Furniture.id == furniture_id).first()

# 更新家具
def update_furniture(db: Session, furniture_id: int, furniture: FurnitureUpdate) -> Optional[Furniture]:
    db_furniture = get_furniture(db, furniture_id)
    if not db_furniture:
        return None
    
    update_data = furniture.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(db_furniture, field, value)
    
    db.commit()
    db.refresh(db_furniture)
    return db_furniture

# 删除家具
def delete_furniture(db: Session, furniture_id: int) -> bool:
    db_furniture = get_furniture(db, furniture_id)
    if not db_furniture:
        return False
    
    db.delete(db_furniture)
    db.commit()
    return True
